/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-02-16
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-03-13
 * @Description: loading动画
 */
import 'dart:math';

import 'package:flutter/material.dart';

// 在 main.dart 的 MaterialApp 中初始化
GlobalKey<NavigatorState> loadingNavigatorKey = GlobalKey();

class Loading {
  static GlobalKey<NavigatorState> _navigatorKey = GlobalKey();
  static OverlayEntry? _overlayEntry;
  static int _showCount = 0; // 支持多个异步任务同时等待的场景

  // 在 main.dart 的 MaterialApp 初始化时调用
  static void initialize({GlobalKey<NavigatorState>? navigatorKey}) {
    _navigatorKey = navigatorKey ?? GlobalKey();
  }

  // 显示加载框（可在任何地方无 context 调用）
  static void show({String message = 'Loading...'}) {
    _showCount++;
    if (_overlayEntry != null) return;

    _ensureOverlayState(() {
      _overlayEntry?.remove();
      _overlayEntry = OverlayEntry(
        builder: (context) => _ElegantLoader(message: message),
      );

      // 插入到最上层 Overlay
      _navigatorKey.currentState?.overlay?.insert(_overlayEntry!);

      // 自动隐藏保护（防止永远不调用 hide）
      Future.delayed(const Duration(seconds: 30)).then((_) => hide());
    });
  }

  // 隐藏加载框（安全调用，多次调用不会报错）
  static void hide() {
    if (_showCount > 0) _showCount--;
    if (_showCount != 0) return;

    _ensureOverlayState(() {
      _overlayEntry?.remove();
      _overlayEntry = null;
    });
  }

  // 安全操作 Overlay 状态
  static void _ensureOverlayState(VoidCallback action) {
    final overlay = _navigatorKey.currentState?.overlay;
    if (overlay == null) {
      print('Loading Error: Navigator key not attached to overlay');
      return;
    }
    action();
  }

  // 获取当前上下文（用于需要 context 的操作）
  static BuildContext? get context =>
      _navigatorKey.currentState?.overlay?.context;
}

class _ElegantLoader extends StatefulWidget {
  final String message;

  const _ElegantLoader({required this.message});

  @override
  __ElegantLoaderState createState() => __ElegantLoaderState();
}

class __ElegantLoaderState extends State<_ElegantLoader>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  final List<Color> _colors = [
    Colors.blueAccent,
    Colors.purpleAccent,
    Colors.pinkAccent,
    Colors.cyanAccent,
  ];

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    )..repeat();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AbsorbPointer(
      child: Container(
        color: Colors.black54,
        child: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox(
                width: 120,
                height: 120,
                child: CustomPaint(
                  painter: _OrbitalLoaderPainter(
                    animation: _controller,
                    colors: _colors,
                  ),
                ),
              ),
              const SizedBox(height: 24),
              Text(
                widget.message,
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 24,
                  fontWeight: FontWeight.w500,
                  decoration: TextDecoration.none,
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

class _OrbitalLoaderPainter extends CustomPainter {
  final Animation<double> animation;
  final List<Color> colors;

  _OrbitalLoaderPainter({
    required this.animation,
    required this.colors,
  }) : super(repaint: animation);

  @override
  void paint(Canvas canvas, Size size) {
    final center = size.center(Offset.zero);
    final radius = size.width / 3;
    const dotCount = 8;
    const dotSize = 6.0;

    // 主轨道旋转
    final angle = 2 * pi * animation.value;

    // 绘制轨迹线
    final trackPaint = Paint()
      ..color = Colors.white.withValues(alpha: 0.1)
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1.5;

    canvas.drawCircle(center, radius, trackPaint);

    // 绘制动态粒子
    for (var i = 0; i < dotCount; i++) {
      final color = colors[i % colors.length];
      final offsetAngle = angle + (i * pi / dotCount * 2);
      final position = Offset(
        center.dx + radius * cos(offsetAngle),
        center.dy + radius * sin(offsetAngle),
      );

      // 粒子大小变化
      final sizeFactor = 0.6 + 0.4 * sin(animation.value * 2 * pi + i);
      final dotPaint = Paint()
        ..color = color.withValues(alpha: 0.8)
        ..maskFilter = const MaskFilter.blur(BlurStyle.normal, 2);

      canvas.drawCircle(
        position,
        dotSize * sizeFactor,
        dotPaint,
      );
    }

    // 中心渐变球体
    final gradientPaint = Paint()
      ..shader = RadialGradient(
        colors: [colors.first.withValues(alpha: 0.4), Colors.transparent],
      ).createShader(Rect.fromCircle(center: center, radius: radius / 2));

    canvas.drawCircle(center, radius / 3, gradientPaint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
